import type { getRoleParams, RoleResponse, RoleStructure } from "@/api/role.ts"
import {
  addRoleApi,
  deleteRoleApi,
  getRoleListApi,
  updateRoleApi
} from "@/api/role.ts"

export const useRoleStore = defineStore("role", () => {
  const state = reactive<RoleResponse>({
    list: [],
    total: 0
  })

  const getRoleList = async (params: getRoleParams) => {
    const res = await getRoleListApi(params)
    const { data } = res
    state.list = data.list
    state.total = data.total
  }

  const addRole = async (data: RoleStructure & getRoleParams) => {
    const { page, pageSize, ...role } = data
    const res = await addRoleApi(role)
    if (res.code === 200) {
      getRoleList({ page, pageSize })
    }
  }

  const updateRole = async (data: RoleStructure & getRoleParams) => {
    const { page, pageSize, ...role } = data
    const res = await updateRoleApi(role)
    if (res.code === 200) {
      getRoleList({ page, pageSize })
    }
  }

  const deleteRole = async (data: RoleStructure & getRoleParams) => {
    const { id, page, pageSize } = data
    const res = await deleteRoleApi(id)
    if (res.code === 200) {
      getRoleList({ page, pageSize })
    }
  }

  return {
    state,
    getRoleList,
    addRole,
    updateRole,
    deleteRole
  }
})
